package 牛客题霸;

public class 链表内指定区间反转 {

    public ListNode reverseBetween (ListNode head, int m, int n) {
        if(head == null) {
            return null;
        }
        ListNode dum = new ListNode(-1);
        dum.next = head;

        ListNode pre = dum;
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }

        ListNode right = pre;
        for (int i = 0; i < n - m + 1; i++) {
            right = right.next;
        }

        ListNode left = pre.next;
        ListNode cur = right.next;

        pre.next = null;
        right.next = null;

        reverse(left);

        pre.next = right;
        left.next = cur;
        return dum.next;
    }

    public void reverse(ListNode head) {
        ListNode pre = null;
        ListNode dum = head;
        while (dum != null) {
            ListNode temp = dum.next;
            dum.next = pre;
            pre = dum;
            dum = temp;
        }
    }

    public static void main(String[] args) {

    }

    public class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
}
